<template>
  <ContentWrap>
    <el-descriptions :column="1" border label-width="130">
      <el-descriptions-item label="采购类型">
        <el-select v-model="detailData.purchaseType" placeholder="请选择采购类型" :disabled="true">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.PURCHASE_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-descriptions-item>
      <!-- 非小额类 -->
      <template v-if="type == 'NoSmall'">
        <el-descriptions-item label="采购事项名称">
          {{ detailData.planName }}
        </el-descriptions-item>
        <el-descriptions-item label="预算归属部门">
          <el-select
            v-model="detailData.budgetDepartmentId"
            disabled
            filterable
            placeholder="请选择预算归属部门"
          >
            <el-option
              v-for="item in DeptPageList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-descriptions-item>
        <el-descriptions-item label="需求使用部门">
          <el-select
            v-model="detailData.applicationDepartmentId"
            disabled
            filterable
            placeholder="请选择需求使用部门"
          >
            <el-option
              v-for="item in DeptPageList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-descriptions-item>
        <el-descriptions-item label="采购计划编号">
          {{ detailData.planNo }}
        </el-descriptions-item>
        <el-descriptions-item label="项目名称">
          {{ detailData.projectName }}
        </el-descriptions-item>
        <el-descriptions-item label="采购方式">
          <el-select v-model="detailData.purchaseMethod" placeholder="请选择采购方式" disabled>
            <el-option
              v-for="dict in getStrDictOptions(DICT_TYPE.PURCHASE_METHOD)"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-descriptions-item>
        <el-descriptions-item label="质保期/维保期">
          {{ detailData.warrantyPeriod }}
        </el-descriptions-item>
        <el-descriptions-item label="原合同期限">
          <el-date-picker
            disabled
            v-model="detailData.originalContractTime"
            value-format="YYYY-MM-DD"
            type="daterange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
            class="!w-220px"
          />
        </el-descriptions-item>
        <el-descriptions-item label="原合同金额">
          {{ detailData.originalContractAmount }}元
        </el-descriptions-item>
        <el-descriptions-item label="合同使用履约情况">
          {{ detailData.contractPerformance }}
        </el-descriptions-item>
        <el-descriptions-item label="本次采购预估单价来源说明">
          {{ detailData.estimatedPriceSource }}
        </el-descriptions-item>
        <!-- 工程类 -->

        <template v-if="detailData.purchaseType == 'ENGINEERING'">
          <el-descriptions-item>
            <ContentWrap>
              <el-table :data="detailData.engineeringDetailSaveReqVOS">
                <el-table-column type="index" label="序号" />
                <el-table-column prop="purchaseContent" label="采购内容（详细）" />
                <el-table-column prop="estimatedQuantity" label="预估采购数量" />
                <el-table-column
                  prop="totalPriceLimit"
                  label="总价限价（单位：万元，人民币）"
                  min-width="160"
                />
                <el-table-column prop="remark" label="备注" />
              </el-table>
            </ContentWrap>
          </el-descriptions-item>
          <div style="display: flex">
            <el-descriptions-item label="需到货时间" prop="requiredDeliveryTime" style="flex: 1">
              <el-date-picker
                v-model="detailData.requiredDeliveryTime"
                value-format="YYYY-MM-DD"
                type="date"
                placeholder="选择需到货时间"
                disabled
              />
            </el-descriptions-item>
            <el-descriptions-item
              label="是否含有非标配件"
              prop="hasNonStandardParts"
              style="flex: 1; margin-left: 20px"
            >
              <el-checkbox
                v-model="detailData.hasNonStandardParts"
                true-value="1"
                false-value="0"
                label="请确认"
                disabled
              />
            </el-descriptions-item>
          </div>
          <div style="display: flex">
            <el-descriptions-item label="施工时间" prop="constructionTime" style="flex: 1">
              <el-date-picker
                v-model="detailData.constructionTime"
                value-format="YYYY-MM-DD"
                type="date"
                disabled
                placeholder="选择施工时间"
              />
            </el-descriptions-item>
            <el-descriptions-item
              label="是否含暂列金"
              prop="hasProvisionalSum"
              style="flex: 1; margin-left: 20px"
            >
              <el-checkbox
                disabled
                v-model="detailData.hasProvisionalSum"
                true-value="1"
                false-value="0"
                label="请确认"
              />
            </el-descriptions-item>
          </div>
          <el-descriptions-item label="施工日期" prop="construction">
            <el-date-picker
              disabled
              v-model="detailData.construction"
              value-format="YYYY-MM-DD"
              type="daterange"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
              class="!w-220px"
            />
            <el-button disabled>{{ dayLength }}天</el-button>
          </el-descriptions-item>
          <el-descriptions-item label="施工期间负责人" prop="constructionLeader">
            {{ detailData.constructionLeader }}
          </el-descriptions-item>
        </template>

        <!-- 服务类 -->
        <template v-if="detailData.purchaseType == 'SERVICE'">
          <el-descriptions-item>
            <ContentWrap>
              <el-table :data="detailData.serviceDetailSaveReqVOS">
                <el-table-column type="index" label="序号" />
                <el-table-column prop="purchaseContent" label="采购内容（详细）" width="200" />
                <el-table-column prop="servicePeriod" label="服务期限" width="200" />
                <el-table-column prop="serviceLocation" label="服务地点" width="200" />
                <el-table-column prop="supplierQualification" label="供应商资质要求" width="200" />
                <el-table-column prop="technicalReview" label="技术评审单" width="200" />
                <el-table-column prop="currentInventory" label="现有库存数量" width="200" />
                <el-table-column prop="unit" label="单位" />
                <el-table-column prop="estimatedQuantity" label="预估采购数量" align="center" />
                <el-table-column
                  prop="estimatedUnitPrice"
                  label="预估单价（元/含税）"
                  align="center"
                  width="200"
                />
                <el-table-column prop="totalAmount" label="合计" align="center" width="200" />
              </el-table>
            </ContentWrap>
          </el-descriptions-item>
        </template>
        <!-- 物资类 -->
        <template v-if="detailData.purchaseType == 'MATERIAL'">
          <el-descriptions-item>
            <ContentWrap>
              <el-table :data="detailData.materialDetailSaveReqVOS">
                <el-table-column type="index" label="序号" />
                <el-table-column prop="materialCode" label="物料编码（NC编码）" width="160" />
                <el-table-column
                  prop="materialName"
                  label="物料名称（与NC编码中对应上）"
                  width="240"
                />
                <el-table-column prop="unit" label="单位" />
                <el-table-column
                  prop="specification"
                  label="规格(产品的最小包装规格)"
                  width="200"
                />
                <el-table-column prop="acceptanceStandard" label="物料/收货标准" width="200" />

                <el-table-column prop="brandRequirements" label="产品要求或参考品牌" width="200" />
                <el-table-column
                  prop="packagingRequirements"
                  label="送货/产品外包装要求"
                  width="200"
                />
                <el-table-column
                  prop="estimatedQuantity"
                  label="预估采购数量（年用量）"
                  align="center"
                  width="200"
                />
                <el-table-column
                  prop="estimatedUnitPrice"
                  label="预估单价/限价（元/含税）"
                  width="200"
                  align="center"
                />
                <el-table-column prop="totalAmount" label="合计" width="220" />
              </el-table>
            </ContentWrap>
          </el-descriptions-item>
        </template>
        <!-- 设备类 -->
        <template v-if="detailData.purchaseType == 'EQUIPMENT'">
          <el-descriptions-item>
            <ContentWrap>
              <el-table :data="detailData.equipmentDetailSaveReqVOS">
                <el-table-column type="index" label="序号" />
                <el-table-column prop="category" label="分类" width="120" />
                <el-table-column prop="equipmentName" label="设备名称" width="120" />
                <el-table-column prop="unit" label="单位" />
                <el-table-column prop="parameterRequirements" label="参数要求" width="200" />
                <el-table-column prop="supplierQualification" label="供应商资质要求" width="200" />
                <el-table-column
                  prop="reviewRequirements"
                  label="商务或技术评审点要求"
                  width="200"
                />
                <el-table-column
                  prop="estimatedQuantity"
                  label="预估采购数量"
                  align="center"
                  width="200"
                />
                <el-table-column
                  prop="estimatedUnitPrice"
                  label="预估单价（元/含税）"
                  align="center"
                  width="200"
                />
                <el-table-column prop="totalAmount" label="合计" align="center" width="200" />
              </el-table>
            </ContentWrap>
          </el-descriptions-item>
        </template>
      </template>
      <template v-if="type == 'Small'">
        <el-descriptions-item label="采购事项名称">
          {{ detailData.planName }}
        </el-descriptions-item>
        <template v-if="detailData.purchaseType == 'DIRECT'">
          <el-descriptions-item label="实施小组组成">
            {{ detailData.implementationTeam }}
          </el-descriptions-item>
          <el-descriptions-item label="谈判报价方式">
            {{ detailData.negotiationMethod }}
          </el-descriptions-item>
          <el-descriptions-item label="供应商选择原则">
            {{ detailData.supplierSelectionPrinciple }}
          </el-descriptions-item>
        </template>
        <el-descriptions-item label="项目理由">
          {{ detailData.projectReason }}
        </el-descriptions-item>
        <el-descriptions-item>
          <ContentWrap>
            <el-table :data="detailData.minorDetailSaveReqVOS">
              <el-table-column type="index" label="序号" />
              <el-table-column prop="itemName" label="物料/服务/工程名称" width="200" />
              <el-table-column prop="unit" label="单位" />
              <el-table-column prop="specModel" label="规格型号" />
              <el-table-column prop="acceptanceStandard" label="货物/验收标准" width="200" />
              <el-table-column prop="originPlace" label="产地" width="200" />
              <el-table-column prop="estimatedQuantity" label="预估采购数量" align="center" />
              <el-table-column
                prop="estimatedUnitPrice"
                label="预估单价（含税/万元）"
                align="center"
                width="200"
              />
              <el-table-column
                prop="totalAmount"
                label="合计（含税/万元）"
                align="center"
                width="200"
              />
            </el-table>
          </ContentWrap>
        </el-descriptions-item>
      </template>
      <el-descriptions-item label="备注说明">
        {{ detailData.remark }}
      </el-descriptions-item>
    </el-descriptions>
  </ContentWrap>
</template>
<script lang="ts" setup>
import { propTypes } from '@/utils/propTypes'
import { getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import { PurchasePlanApi, PurchasePlanSaveReqVO } from '@/api/erp/purchase/plan'
import { formatDate } from '@/utils/formatTime.js'
import { getDeptPage, DeptVO, getSimpleDeptList } from '@/api/system/dept'

defineOptions({ name: 'SupplierDetail' })

const { query } = useRoute() // 查询参数

const props = defineProps({
  id: propTypes.string.def(undefined)
})
const detailLoading = ref(false) // 表单的加载中
const detailData = ref<any>({}) // 详情数据
const queryId = query.id as unknown as number // 从 URL 传递过来的 id 编号

/** 获得数据 */
const getInfo = async () => {
  detailLoading.value = true
  try {
    detailData.value = await PurchasePlanApi.getPurchasePlan(props.id || queryId)
    timeRangeConfigs.forEach(({ start, end, target }) => {
      const hasStart = typeof detailData.value[start] === 'number'
      const hasEnd = typeof detailData.value[end] === 'number'
      if (hasStart && hasEnd) {
        detailData.value[target] = [
          formatDate(detailData.value[start], 'YYYY-MM-DD'),
          formatDate(detailData.value[end], 'YYYY-MM-DD')
        ]
      } else if (hasStart) {
        detailData.value[target] = [formatDate(detailData.value[start]), null, 'YYYY-MM-DD']
      } else if (hasEnd) {
        detailData.value[target] = [null, formatDate(detailData.value[end]), 'YYYY-MM-DD']
      }
    })
    const singleTimeFields = ['constructionTime', 'requiredDeliveryTime']
    singleTimeFields.forEach((field) => {
      if (typeof detailData.value[field] === 'number') {
        detailData.value[field] = formatDate(detailData.value[field], 'YYYY-MM-DD')
      }
    })
    const currentPurchaseType = detailData.value.purchaseType
    const respListKey = respListMap[currentPurchaseType]
    const saveListKey = typeMap[currentPurchaseType]
    if (respListKey && saveListKey) {
      detailData.value[saveListKey] = detailData.value[respListKey] || []
    } else {
      console.error(`未找到采购类型【${currentPurchaseType}】对应的列表字段映射`)
    }
  } finally {
    detailLoading.value = false
  }
}
defineExpose({ open: getInfo }) // 提供 open 方法，用于打开弹窗

/** 获取部门列表 */
const DeptPageList = ref<DeptVO[]>([])
const getDeptPageApi = async () => {
  try {
    const data = await getSimpleDeptList()
    DeptPageList.value = data
  } finally {
  }
}

/** 打开弹窗 */
const timeRangeConfigs = [
  {
    start: 'originalContractStartTime',
    end: 'originalContractEndTime',
    target: 'originalContractTime'
  },
  { start: 'constructionStartTime', end: 'constructionEndTime', target: 'construction' }
]
/* 获取数据时子列表的映射*/
const respListMap = {
  SERVICE: 'serviceDetailRespVOS',
  EQUIPMENT: 'equipmentDetailRespVOS',
  ENGINEERING: 'engineeringDetailRespVOS',
  MATERIAL: 'materialDetailRespVOS',
  DIRECT: 'minorDetailRespVOS',
  MINOR: 'minorDetailRespVOS'
}
/** 保存数据时的映射 */
const typeMap = {
  SERVICE: 'serviceDetailSaveReqVOS',
  EQUIPMENT: 'equipmentDetailSaveReqVOS',
  ENGINEERING: 'engineeringDetailSaveReqVOS',
  MATERIAL: 'materialDetailSaveReqVOS',
  DIRECT: 'minorDetailSaveReqVOS',
  MINOR: 'minorDetailSaveReqVOS'
}
/* 小额 非 小额切换 */
const type = ref<String>('NoSmall')
const initialdetailData = ref(JSON.parse(JSON.stringify(detailData.value)))
watch(
  () => detailData.value.purchaseType,
  (newValue, oldValue) => {
    type.value = newValue === 'DIRECT' || newValue === 'MINOR' ? 'Small' : 'NoSmall'
    // 切换采购类型时重置表单（排除 purchaseType 字段）
    if (oldValue !== undefined) {
      // 避免初始化时重置
      const resetData = JSON.parse(JSON.stringify(initialdetailData.value))
      detailData.value = {
        ...resetData,
        purchaseType: newValue // 保留当前选择的类型
      }
    }
  },
  {
    immediate: true // 立即执行一次回调
  }
)
/* 监听施工日期变化计算总时长  */
const dayLength = ref(0)
watch(
  () => detailData.value.construction,
  (newValue) => {
    if (newValue && newValue[0] && newValue[1]) {
      const startDate = new Date(newValue[0])
      const endDate = new Date(newValue[1])
      const timeDiff = endDate.getTime() - startDate.getTime()
      dayLength.value = Math.ceil(timeDiff / (1000 * 3600 * 24))
    }
  },
  {
    immediate: true // 立即执行一次回调
  }
)

/** 初始化 **/
onMounted(() => {
  getInfo()
  getDeptPageApi()
})
</script>
